const { ccclass, property } = cc._decorator;
import placeItem from './placeItem';
import WayBaseControl from './WayBaseControl';

@ccclass
export default class placeWayControl extends cc.Component {
    @property(cc.Node)
    waysNode: cc.Node = null;
    @property({
        type: [cc.Component.EventHandler],
        tooltip: "选择后的回调"
    })
    selectEvents: Array<cc.Component.EventHandler> = [];
    nodePool: cc.NodePool = new cc.NodePool();
    placeItemPrefab: cc.Prefab = null;
    wayNode: cc.Node = null;
    offsetUp: number = 15;

    onLoad() {
        this.node.on("onNodeClick", this.emitEvents, this);
    }
    setWay() {
        this.clearItem();
        let id = HeroHelper.getInstance().uuidWayCollider;
        this.wayNode = this.waysNode.getChildByUuid(id);
        let controlWay = this.wayNode.getComponent(WayBaseControl);
        if (this.wayNode) {
            this.node.zIndex = 99;
            this.node.parent = this.wayNode;
            let index = 0;
            let occu = controlWay.getOccupy();
            this.wayNode.children.forEach(element => {
                if (element.name == "way") {
                    if (!occu[index]) {
                        let item = this.getItem();
                        let control = item.getComponent(placeItem);
                        control.tag = index;
                        control.init();
                        item.group = this.node.group;
                        this.setItem(element, item);
                    }
                    index++;
                }
            });
        }
    }
    clearItem() {
        let length = this.node.children.length;
        for (let i = 0; i < length; i++) {
            this.nodePool.put(this.node.children[0]);
        }
    }
    getItem(): cc.Node {
        if (this.nodePool.size() > 0) {
            return this.nodePool.get();
        }
        else {
            return cc.instantiate(this.placeItemPrefab);
        }
    }
    setItem(way: cc.Node, item: cc.Node) {
        item.x = way.x;
        item.y = way.height / 2 - this.offsetUp;
        this.node.addChild(item);
    }
    private emitEvents(event: cc.Event.EventCustom) {
        let date = event.getUserData();
        cc.Component.EventHandler.emitEvents(this.selectEvents, {
            target: this,
            tag: date.tag,
            wayId: this.wayNode.uuid,
            position: date.position
        });
        event.stopPropagation();
    }
}
